package com.yf.ccdugtfood.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yf.ccdugtfood.R;
import com.yf.ccdugtfood.bean.User;
import com.yf.ccdugtfood.ui.home.HomeFragment;
import com.yf.ccdugtfood.ui.me.MeFragment;
import com.yf.ccdugtfood.util.Constant;
import com.yf.ccdugtfood.util.SharedPreferencesUser;
import com.yf.ccdugtfood.util.VerificationCode;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

public class LoginActivity extends AppCompatActivity implements View.OnClickListener{
    private TextView register;
    private TextView forgetPw;
    private ImageView image_code;
    private Button change_code,login;
    private EditText et_userPhone, et_password, VF_Code;
    private String user_phone,password,vf_code;
    private String user_phone_out,password_out;
    public static final int MSG_SUCCESS_OK = 2;
    private List<User> userList;
    private Type typeList;
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            if (msg.what==MSG_SUCCESS_OK){
                if (msg.obj!=null){
                    String result = msg.obj.toString();
                    Gson gson = new Gson();
                    typeList = new TypeToken<List<User>>(){}.getType();
                    userList = gson.fromJson(result,typeList);
                    String id,user_name,user_phone;
                    for(User user : userList){
                        id = String.valueOf(user.getId());
                        user_name = user.getUser_name();
                        user_phone =user.getUser_phone();
                        SharedPreferencesUser.saveUserInfo(LoginActivity.this,id,user_name,user_phone);
                    }
                    Toast.makeText(LoginActivity.this,"登录成功!",Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                    startActivity(intent);
                }else {
                    Toast.makeText(LoginActivity.this,"登录失败!",Toast.LENGTH_SHORT).show();
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        et_userPhone = findViewById(R.id.et_userPhone);
        et_password = findViewById(R.id.et_password);
        VF_Code = findViewById(R.id.code);

        register = (TextView)findViewById(R.id.go_register);
        forgetPw = findViewById(R.id.tv_forgetPw);
        image_code = (ImageView) findViewById(R.id.image_code);
        change_code = (Button) findViewById(R.id.change_code);
        login = (Button) findViewById(R.id.login);

        image_code.setOnClickListener(this);
        forgetPw.setOnClickListener(this);
        register.setOnClickListener(this);
        change_code.setOnClickListener(this);
        login.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.go_register:
                Intent intent = new Intent(LoginActivity.this,RegisterActivity.class);
                startActivity(intent);
                break;
            case R.id.tv_forgetPw:
                Toast.makeText(LoginActivity.this,"请联系管理员！",Toast.LENGTH_SHORT).show();
                break;
            case R.id.image_code:
                image_code.setImageBitmap(VerificationCode.getVerificationCode());
                break;
            case R.id.change_code:
                image_code.setImageBitmap(VerificationCode.getVerificationCode());
                break;
            case R.id.login:
                if (VerificationCode.checkVerificationCode(VF_Code.getText()
                        .toString())){
                    user_phone = et_userPhone.getText().toString();
                    password = et_password.getText().toString();
                    vf_code = VF_Code.getText().toString();
                    if(user_phone.length()==0) {
                        Toast.makeText(LoginActivity.this, "请输入注册时使用的手机号码！", Toast.LENGTH_SHORT).show();
                    }else if (password.length()==0){
                        Toast.makeText(LoginActivity.this, "请输入密码！", Toast.LENGTH_SHORT).show();
                    }else if (vf_code.length()==0){
                        Toast.makeText(LoginActivity.this, "请输入验证码！", Toast.LENGTH_SHORT).show();
                    }else if (!"".equals(user_phone) && !"".equals(password)){
                        login();
                    }
                }else{
                    Toast.makeText(LoginActivity.this, "验证码错误！", Toast.LENGTH_SHORT).show();
                    image_code.setImageBitmap(VerificationCode.getVerificationCode());
                    VF_Code.setText("");
                }

        }
    }

    private void login() {
        new Thread(){
            @Override
            public void run() {
                try {
                    user_phone_out = et_userPhone.getText().toString();
                    password_out = et_password.getText().toString();
                    String data = "user_phone="+URLEncoder.encode(user_phone_out,"utf-8")+"&password="+URLEncoder.encode(password_out,"utf-8");
                    URL url = new URL(Constant.WEB_SITE+Constant.REQUEST_LOGIN);
                    HttpURLConnection coon = (HttpURLConnection) url.openConnection();
                    // 设置允许输出
                    coon.setDoOutput(true);
                    coon.setRequestMethod("POST");
                    coon.setConnectTimeout(10000);
                    // 设置不用缓存
                    coon.setUseCaches(false);
                    coon.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    coon.setRequestProperty("Content-Length", data.length()+"");
                    coon.setDoOutput(true);
                    // 开始连接请求
                    coon.connect();
                    OutputStream os = coon.getOutputStream();
                    os.write(data.getBytes());
                    int responseCode = coon.getResponseCode();
                    if (responseCode==200){
                        BufferedReader reader = new BufferedReader(new InputStreamReader((coon.getInputStream()),"utf-8"));
                        StringBuilder sb= new StringBuilder();
                        String line;
                        while ((line=reader.readLine())!=null){
                            line = new String(line.getBytes(),"utf-8");
                            sb.append(line);
                        }
                        Log.i("aa",new String(sb));
                        Message msg = handler.obtainMessage();
                        msg.what = MSG_SUCCESS_OK;
                        msg.obj = sb;
                        handler.sendMessage(msg);
                    }
                    coon.disconnect();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }.start();
    }
}
